package edu.haiu.training.data;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class Edit {
	private static final String username1 ="root";
	private static final String password1 ="123456";
	private static final String database1 ="jdbc:mysql://localhost:3306/mydb";
	
	List<User>users = new ArrayList<User>();
	
	public List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}
	public String edit() throws Exception{
		//Hiển thị bảng dữ liệu 
		Connection connection = DriverManager.getConnection(database1,username1,password1);
		String qs= "select * from mydb.user";
		PreparedStatement st= connection.prepareStatement(qs);
		ResultSet rs = st.executeQuery(qs);
		
		while(rs.next()){
			 User user = new User();
			 user.setId1(rs.getInt("Id"));
			 user.setUsername(rs.getString("Username"));
			 user.setPassword(rs.getString("Password"));
			 user.setFirstName(rs.getString("FirstName"));
			 user.setLastName(rs.getString("LastName"));
			 user.setAddress(rs.getString("Address"));
			 user.setBirthday(String.valueOf(new java.sql.Date(rs.getDate("Birthday").getTime())));
			 user.setAdministrator(rs.getBoolean("Administrator"));		 
			 user.setState(UserState.values()[rs.getInt("State")]);
			 users.add(user);
		}
		// Nhận id 
		
		User user = new User();
		try {
			HttpServletRequest rq = ServletActionContext.getRequest();
			int idUser = Integer.parseInt(rq.getParameter("id3"));
			String username = rq.getParameter("username");
			String password= rq.getParameter("password");
			String firstName= rq.getParameter("firstName");
			String lastName=rq.getParameter("lastName");
			String address=rq.getParameter("address");
			Date birthday = Date.valueOf(rq.getParameter("birthday"));
			Boolean administrator=Boolean.valueOf(rq.getParameter("administrator"));
			UserState state=UserState.valueOf(rq.getParameter("state"));
			user.editUser(idUser,username,password,firstName,lastName,address,birthday,administrator,state);
		} catch(NumberFormatException e) {
			e.printStackTrace();
		}
		return "success";
	}
	
}
